package datastructure.stack;



/**
 * 数组实现stack
 * @author lbw
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(4);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.list();
        System.out.println(stack.pop());
        stack.list();
    }
}

class ArrayStack{
    /**
     * 栈的大小
     */
    private int maxSize;
    /**
     * 数据的存储位置
     */
    private int[] stack;
    /**
     * 栈顶
     */
    private int top = -1;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[maxSize];
    }

    /**
     * 判断栈是否满的
     * @return
     */
    public boolean full(){
        return top == maxSize-1;
    }

    /**
     * 栈空
     * @return
     */
    public boolean empty(){
        return top == -1;
    }

    public void push(int value){
        if (full()){
            System.out.println("栈满了");
            return;
        }
        stack[++top] = value;
    }

    public int pop(){
        if (empty()){
            throw new ArrayIndexOutOfBoundsException();
        }
        return stack[top--];
    }

    public void list(){
        if (empty()){
            System.out.println("栈为空");
            return;
        }
        for (int i = top; i >= 0; i--){
            System.out.printf("stack[%d]", stack[i]);
        }
    }
}